package org.ezplatform.office.meeting.common.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.component.popuser.service.CmpPopUserOrgName;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.mobile.util.common.service.CommonService;
import org.ezplatform.sdk.AccessToken;
import org.ezplatform.sdk.Client;
import org.ezplatform.sdk.exception.AuthException;
import org.ezplatform.util.CacheUtils;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.RestClient;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MeetingSendMsgUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(MeetingSendMsgUtils.class);
	
	private static String moduleType = "meeting";
	
	@Autowired
	private MeetingUtils meetingUtils;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private CmpPopUserOrgName cmpPopUserOrgName;
	
	
	/**
	 * 移动端发消息
	 * @param ds
	 * @param corpId
	 * @param token
	 */
	public void sendMsgToApp(Map<String,Object> ds, boolean mobilePush, String corpId, String token, HttpServletRequest request){
		LOGGER.debug("-------------sendMsgToApp---------------");
        try{
        	//获取系统后台的消息设置(wxWork,ding,evoPortal)
        	String sysNoticeType = commonService.getSysParamValueByMark(corpId, token,"sysImType");
        	LOGGER.debug("---sysNoticeType:"+sysNoticeType);
        	LOGGER.debug("---mobilePush:"+mobilePush);
        	boolean mobileset = meetingUtils.getAppInfoMessageSet(corpId, token,"mobile");
        	LOGGER.debug("---mobileset:"+mobileset);
        	if(StringUtils.isEmpty(sysNoticeType) || !mobilePush || !mobileset) return ;
        	Map<String,String> msgTypeMap = new HashMap<String, String>();
        	Map<String,Object> messageMap = new HashMap<String, Object>();
            
            String messageUrl = "";
            String context = "";
            //链接ip
            String fullPath = GlobalConstant.getFlexOfficeFullPath(request);
            LOGGER.debug("---fullPath:"+fullPath);
        	context = convertContextPath(fullPath);
        	LOGGER.debug("---context:"+context);
//        	System.out.println("JSH666webUrl=" + webUrl);
        	String type = StringUtils.null2String(ds.get("type"));
//        	if("1".equals(type)){//审批
//        		String pathTime = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
//        		messageUrl = "/mobile/meeting/dist/index.html?" + context
//        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/meetingDetails"
//        				+ "/" + ds.get("applyRecordId").toString()
//        				+ "/approve/"+pathTime;
//        	}else 
        	String pcurl = "";
        	if("2".equals(type)){//参会邀请
        		messageUrl = "/mobile/modules/meeting/dist/index.html?contextPath=" + context
        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/meetingDetails"
        				+ "/" + ds.get("applyRecordId").toString()
        				+ "/notice/message";
        		pcurl = "/web/dist/modules/meeting/info/applyrecord_view_msg.html?window&applyRecordId="+ds.get("applyRecordId").toString();
        	}else if("3".equals(type)){//取消会议
        		messageUrl = "/mobile/modules/meeting/dist/index.html?contextPath=" + context
        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/myMeetingDetails"
        				+ "/" + ds.get("applyRecordId").toString()
        				+ "/myJoinIn/message";
        		pcurl = "/web/dist/modules/meeting/info/applyrecord_view_msg.html?window&applyRecordId="+ds.get("applyRecordId").toString();
        	}else if("4".equals(type)){//会前提醒
        		messageUrl = "/mobile/modules/meeting/dist/index.html?contextPath=" + context
        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/meetingDetails"
        				+ "/" + ds.get("applyRecordId").toString()
        				+ "/notice/message";
        		pcurl = "/web/dist/modules/meeting/info/applyrecord_view_msg.html?window&applyRecordId="+ds.get("applyRecordId").toString();
        	}else if("5".equals(type)){//会议纪要
        		messageUrl = "/mobile/modules/meeting/dist/index.html?contextPath=" + context
        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/meetingMemo"
        				+ "/" + ds.get("applyRecordId").toString()
        				+ "/" + ds.get("id").toString()
        				+ "/view/message";
        		pcurl = "/web/dist/modules/meeting/info/applyrecord_view_msg.html?window&applyRecordId="+ds.get("applyRecordId").toString();
        	}else if("6".equals(type)){//会议任务
        		messageUrl = "/mobile/modules/meeting/dist/index.html?contextPath=" + context
        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/taskView"
        				+ "/" + ds.get("id").toString()
        				+ "/" + ds.get("applyRecordId").toString()
        				+ "/mine/message";
        		pcurl = "/web/dist/modules/meeting/task/taskinfo_view_msg.html?window&id="+ds.get("id").toString()+"&applyRecordId="+ds.get("applyRecordId").toString();
        	}else if("7".equals(type)){//会议任务到期提醒
        		messageUrl = "/mobile/modules/meeting/dist/index.html?contextPath=" + context
        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/taskView"
        				+ "/" + ds.get("id").toString()
        				+ "/" + ds.get("applyRecordId").toString()
        				+ "/mine/message";
        		pcurl = "/web/dist/modules/meeting/task/taskinfo_view_msg.html?window&id="+ds.get("id").toString()+"&applyRecordId="+ds.get("applyRecordId").toString();
        	}else if("8".equals(type)){//会议转交通知
        		messageUrl = "/mobile/modules/meeting/dist/index.html?contextPath=" + context
        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/meetingDetails"
        				+ "/" + ds.get("applyRecordId").toString()
        				+ "/notice/message";
        		pcurl = "/web/dist/modules/meeting/info/applyrecord_view_msg.html?window&applyRecordId="+ds.get("applyRecordId").toString();
        	}else if("9".equals(type)){//会议内容变更提醒
        		Long time = new Date().getTime();//这个时间用来变更消息体内容，如果消息体内容不变，消息将无法重复次发送
        		messageUrl = "/mobile/modules/meeting/dist/index.html?contextPath=" + context
        				+ "&time=" + time
        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/meetingDetails"
        				+ "/" + ds.get("applyRecordId").toString()
        				+ "/notice/message";
        		pcurl = "/web/dist/modules/meeting/info/applyrecord_view_msg.html?window&applyRecordId="+ds.get("applyRecordId").toString();
        	}else if("10".equals(type)){//发送提醒
        		messageUrl = "/mobile/modules/meeting/dist/index.html?contextPath=" + context
        				+ "&dd_nav_bgcolor=FF5E97F6#/meeting/meetingDetails"
        				+ "/" + ds.get("applyRecordId").toString()
        				+ "/notice/message";
        		pcurl = "/web/dist/modules/meeting/info/applyrecord_view_msg.html?window&applyRecordId="+ds.get("applyRecordId").toString();
        	}
        	
        	
        	if(sysNoticeType.contains("ding")) {//钉钉
            	msgTypeMap.put("DING", "oa");
//            	String webUrl = GlobalConstant.getConfig("app.mobile.ding.front.url");
            	Map<String,Object> dingMessageContent = this.getDingMessageContent(ds, messageUrl,pcurl,type);
            	messageMap.put("DING", dingMessageContent);
        	}
        	if(sysNoticeType.contains("wxWork")) {//企业微信
        		msgTypeMap.put("WX", "news");
//        		String weixinFront = GlobalConstant.getConfig("app.mobile.weixin.front.url");
            	Map<String,Object> wxMessageContent = this.getWxOrMhMessageContent(ds, messageUrl,pcurl,type,"WX");
            	messageMap.put("WX", wxMessageContent);
        	}
        	if(sysNoticeType.contains("evoPortal")) {//移动平台
        		msgTypeMap.put("MH", "news");
//        		String menhuFront = GlobalConstant.getConfig("app.mobile.menhu.front.url");
            	Map<String,Object> mhMessageContent = this.getWxOrMhMessageContent(ds, messageUrl,pcurl, type, "MH");
            	messageMap.put("MH", mhMessageContent);
        	}
        	if(sysNoticeType.contains("CoCall")) {//CoCall
        		msgTypeMap.put("COCALL", "news");
//        		String menhuFront = GlobalConstant.getConfig("app.mobile.cocall.front.url");
//        		LOGGER.debug("---menhuFront:"+menhuFront);
            	Map<String,Object> mhMessageContent = this.getWxOrMhMessageContent(ds, messageUrl,pcurl, type, "COCALL");
            	messageMap.put("COCALL", mhMessageContent);
        	}
        	if(sysNoticeType.contains("weLink")) {//WeLink
        		msgTypeMap.put("WLK", "news");
//        		String wlkFront = GlobalConstant.getConfig("app.mobile.wlk.front.url");
//        		LOGGER.debug("---wlkFront:"+wlkFront);
            	Map<String,Object> wlkMessageContent = this.getWxOrMhMessageContent(ds, messageUrl,pcurl, type, "WLK");
            	messageMap.put("WLK", wlkMessageContent);
        	}
        	String userIds = StringUtils.null2String(ds.get("userIds"));
        	String orgIds = StringUtils.null2String(ds.get("orgIds"));
        	SendMsgThread smt = new SendMsgThread(msgTypeMap, messageMap, moduleType, corpId, userIds, orgIds, fullPath, "app");
        	smt.start();
//        	mobileMessageService.sendMobileMsg(corpId, moduleType, userIds, orgIds, msgTypeMap, messageMap, null);
        }catch(Exception e){
            e.printStackTrace();
        }
	}
	
	/**
	 * 钉钉消息体设置
	 * @param ds
	 * @param messageUrl
	 * @param type
	 * @return
	 */
	private Map<String,Object> getDingMessageContent(Map<String,Object> ds, String messageUrl,String pcUrl, String type) {
		Map<String,Object> dingMessageContent = new HashMap<String,Object>();
		String dingMessage = "";
		if("1".equals(type)){//审批
    		String pathTime = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    		dingMessage = "{\"message_url\":\""+messageUrl+"\",\"pcurl\":\""+pcUrl+"\","
    				+"\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"审批通知\"},"
    				+"\"time\": \""+pathTime+"\","
    				+"\"body\": {\"title\":\""+ds.get("userName")+"的会议申请等待您的审批\","
    				+"\"form\": [{\"key\": \"会议名称:\",\"value\": \""+ds.get("meetingTitle").toString()+"\"},{\"key\": \"会议时间:\",\"value\": \""+ds.get("startTime")+"\"},{\"key\": \"会议地点:\",\"value\": \""+ds.get("boardroom")+"\"},{\"key\": \"申请时间:\",\"value\": \""+pathTime+"\"}]"
    				+"}}";
    	}else if("2".equals(type)){//参会邀请
    		dingMessage = "{\"message_url\":\""+messageUrl+"\",\"pcurl\":\""+pcUrl+"\","
    				+"\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"参会邀请\"},"
    				+"\"body\": {\"title\":\""+ds.get("userName")+"邀请您参加"+ds.get("meetingTitle").toString()+"\","
    				+"\"form\": [{\"key\": \"会议时间:\",\"value\": \""+ds.get("startTime")+"\"},{\"key\": \"会议地点:\",\"value\": \""+ds.get("boardroom")+"\"}]"
    				+"}}";
    	}else if("3".equals(type)){//取消会议
    		dingMessage = "{\"message_url\":\""+messageUrl+"\",\"pcurl\":\""+pcUrl+"\","
    				+"\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"会议取消\"},"
    				+"\"body\": {\"title\":\""+ds.get("meetingTitle").toString()+"已取消\","
    				+"\"form\": [{\"key\": \"取消原因:\",\"value\": \""+ds.get("reason")+"\"}]"
    				+"}}";
    	}else if("4".equals(type)){//会前提醒
    		String time = StringUtils.null2String(ds.get("noticeTime"));
			if("5".equals(time)){
				time = "五分钟";
			}else if("10".equals(time)){
				time = "十分钟";
			}else if("30".equals(time)){
				time = "三十分钟";
			}else if("60".equals(time)){
				time = "一小时";
			}
    		dingMessage = "{\"message_url\":\""+messageUrl+"\",\"pcurl\":\""+pcUrl+"\","
    				+"\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"会议提醒\"},"
    				+"\"body\": {\"title\":\""+ds.get("meetingTitle").toString()+"将于"+time+"后召开，请准时参会\","
    				+"\"form\": [{\"key\": \"会议时间:\",\"value\": \""+ds.get("startTime")+"\"},{\"key\": \"会议地点:\",\"value\": \""+ds.get("boardroom")+"\"}]"
    				+"}}";
    	}else if("5".equals(type)){//会议纪要
    		dingMessage = "{\"message_url\":\""+messageUrl+"\",\"pcurl\":\""+pcUrl+"\","
    				+"\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"会议纪要\"},"
    				+"\"body\": {\"title\":\""+ds.get("meetingTitle").toString()+"纪要已发布\","
    				+"\"form\": []"
    				+"}}";
    	}else if("6".equals(type)){//会议任务
    		dingMessage = "{\"message_url\":\""+messageUrl+"\",\"pcurl\":\""+pcUrl+"\","
    				+"\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"会议任务\"},"
    				+"\"body\": {\"title\":\"您有新的会议任务，请尽快完成！\","
    				+"\"form\": [{\"key\": \"任务标题:\",\"value\": \""+ds.get("title")+"\"},{\"key\": \"截止日期:\",\"value\": \""+ds.get("endTime")+"\"},{\"key\": \"所属会议:\",\"value\": \""+ds.get("meetingName")+"\"}]"
    				+"}}";
    	}else if("7".equals(type)){//会议任务到期提醒
    		dingMessage = "{\"message_url\":\""+messageUrl+"\",\"pcurl\":\""+pcUrl+"\","
    				+"\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"参会邀请\"},"
    				+"\"body\": {\"title\":\"您的会议任务即将到期，请尽快完成！\","
    				+"\"form\": [{\"key\": \"任务标题:\",\"value\": \""+ds.get("title")+"\"},{\"key\": \"截止日期:\",\"value\": \""+ds.get("endTime")+"\"},{\"key\": \"所属会议:\",\"value\": \""+ds.get("meetingName")+"\"}]"
    				+"}}";
    	}else if("8".equals(type)){//会议转交通知
    		dingMessage = "{\"message_url\":\""+messageUrl+"\",\"pcurl\":\""+pcUrl+"\","
    				+"\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"参会邀请\"},"
    				+"\"body\": {\"title\":\""+ds.get("userName")+"邀请您代替参加"+ds.get("meetingTitle").toString()+"\","
    				+"\"form\": [{\"key\": \"会议时间:\",\"value\": \""+ds.get("startTime")+"\"},{\"key\": \"会议地点:\",\"value\": \""+ds.get("boardroom")+"\"}]"
    				+"}}";
    	}else if("9".equals(type)){//会议内容变更提醒
    		dingMessage = "{\"message_url\":\""+messageUrl+"\",\"pcurl\":\""+pcUrl+"\","
    				+"\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"会议提醒\"},"
    				+"\"body\": {\"title\":\"变更通知:" + ds.get("meetingTitle").toString()+"安排已变更，请及时确认！\","
    				+"\"form\": [{\"key\": \"会议时间:\",\"value\": \""+ds.get("startTime")+"\"},"
    				+ "{\"key\": \"会议地点:\",\"value\": \""+ds.get("boardroom")+"\"}]" 
    				+"}}";
    	}else if("10".equals(type)){//发送提醒
    		dingMessage = "{\"message_url\":\""+messageUrl+"\",\"pcurl\":\""+pcUrl+"\","
    				+"\"head\": {\"bgcolor\":\"4D98C9\",\"text\": \"会议提醒\"},"
    				+"\"body\": {\"title\":\"" + ds.get("meetingTitle").toString()+"提醒：" + ds.get("meetingRemindContext") + "\","
    				+"\"form\": []"
    				+"}}";
    	}
		dingMessageContent.put("oa", JsonUtils.readValue(dingMessage));
		return dingMessageContent;
	}
	
	/**
	 * 微信或移动平台消息体设置
	 * @param ds
	 * @param messageUrl
	 * @param type
	 * @return
	 */
	private Map<String,Object> getWxOrMhMessageContent(Map<String,Object> ds, String messageUrl,String pcUrl, String type, String sign) {
		Map<String,Object> messageContent = new HashMap<String,Object>();
		String message = "";
		String url = "WX".equals(sign) ? "url" : "appUrl";
		String br = getBR(sign);
		String space = getSpace(sign);
		if("1".equals(type)){//审批
    		String pathTime = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    		message = "{\"articles\" : [{" + 
    					"\"title\" : \"审批通知\"," + 
    					"\"description\" : \"" +br+ ds.get("userName") + "的会议申请等待您的审批" + 
    						"会议名称:" + ds.get("meetingTitle").toString() +
    						"会议时间:" + ds.get("startTime").toString() +
    						"会议地点:" + ds.get("boardroom").toString() +
    						"申请时间:" + pathTime +"\"," + 
    					"\"" + url + "\" : \"" + messageUrl + "\"," + 
    					"\"pcurl\" : \"" + pcUrl + "\"" + 
    				"}]}";
    	}else if("2".equals(type)){//参会邀请
    		message = "{\"articles\" : [{" + 
    					"\"title\" : \"参会邀请\"," + 
    					"\"description\" : \"" +br+ ds.get("userName") + "邀请您参加" + ds.get("meetingTitle").toString() + space +
    						"会议时间:" + ds.get("startTime").toString() + space + 
    						"会议地点:" + ds.get("boardroom").toString() +
    					"\"," + 
    					"\"" + url + "\" : \"" + messageUrl + "\"," + 
    	    			"\"pcurl\" : \"" + pcUrl + "\"" + 
    				"}]}";
    	}else if("3".equals(type)){//取消会议
    		message = "{\"articles\" : [{" + 
    					"\"title\" : \"会议取消\"," + 
    					"\"description\" : \"" +br+ (StringUtils.isNotBlank(StringUtils.null2String(ds.get("customMessage")))?ds.get("customMessage"):(ds.get("meetingTitle").toString() + "已取消") )+ space +
    						"取消原因:" + ds.get("reason").toString() +
    					"\"," + 
    					"\"" + url + "\" : \"" + messageUrl + "\"," + 
    	    			"\"pcurl\" : \"" + pcUrl + "\"" + 
    				"}]}";
    	}else if("4".equals(type)){//会前提醒
    		String time = StringUtils.null2String(ds.get("noticeTime"));
			if("5".equals(time)){
				time = "五分钟";
			}else if("10".equals(time)){
				time = "十分钟";
			}else if("30".equals(time)){
				time = "三十分钟";
			}else if("60".equals(time)){
				time = "一小时";
			}
    		message = "{\"articles\" : [{" + 
					"\"title\" : \"会议提醒\"," + 
					"\"description\" : \"" +br+ ds.get("meetingTitle").toString()+"将于"+time+"后召开，请准时参会" + space +
						"会议时间:" + ds.get("startTime").toString() + space + 
	    				"会议地点:" + ds.get("boardroom").toString() +
					"\"," + 
					"\"" + url + "\" : \"" + messageUrl + "\"," + 
	    			"\"pcurl\" : \"" + pcUrl + "\"" + 
				"}]}";
    	}else if("5".equals(type)){//会议纪要
    		message = "{\"articles\" : [{" + 
					"\"title\" : \"会议纪要\"," + 
					"\"description\" : \"" +br+ ds.get("meetingTitle").toString() + "纪要已发布" + 
					"\"," + 
					"\"" + url + "\" : \"" + messageUrl + "\"," + 
	    			"\"pcurl\" : \"" + pcUrl + "\"" + 
				"}]}";
    	}else if("6".equals(type)){//会议任务
    		message = "{\"articles\" : [{" + 
					"\"title\" : \"会议任务\"," + 
					"\"description\" : \""+br+"您有新的会议任务，请尽快完成" + space + 
						"任务标题:" + ds.get("title").toString() + space + 
	    				"截止日期:" + ds.get("endTime").toString() + space +
	    				"所属会议:" + ds.get("meetingName").toString() +
					"\"," + 
					"\"" + url + "\" : \"" + messageUrl + "\"," + 
	    			"\"pcurl\" : \"" + pcUrl + "\"" + 
				"}]}";
    	}else if("7".equals(type)){//会议任务到期提醒
    		message = "{\"articles\" : [{" + 
					"\"title\" : \"会议任务\"," + 
					"\"description\" : \""+br+"您的会议任务即将到期，请尽快完成" + space +
						"任务标题:" + ds.get("title").toString() + space + 
	    				"截止日期:" + ds.get("endTime").toString() + space +
	    				"所属会议:" + ds.get("meetingName").toString() +
					"\"," + 
					"\"" + url + "\" : \"" + messageUrl + "\"," + 
	    		    "\"pcurl\" : \"" + pcUrl + "\"" + 
				"}]}";
    	}else if("8".equals(type)){//会议转交通知
    		message = "{\"articles\" : [{" + 
					"\"title\" : \"参会邀请\"," + 
					"\"description\" : \""+br + ds.get("userName").toString() + "邀请您代替参加" + ds.get("meetingTitle").toString() + space +
						"会议时间:" + ds.get("startTime").toString() + space +
	    				"会议地点:" + ds.get("boardroom").toString() + 
					"\"," + 
					"\"" + url + "\" : \"" + messageUrl + "\"," + 
	    			"\"pcurl\" : \"" + pcUrl + "\"" + 
				"}]}";
    	}else if("9".equals(type)){//会议内容变更提醒
    		message = "{\"articles\" : [{" + 
					"\"title\" : \"会议提醒\"," + 
					"\"description\" : \""+br+"变更通知:" + ds.get("meetingTitle").toString() + "安排已变更，请及时确认" + space +
						"会议时间:" + ds.get("startTime").toString() + space +
	    				"会议地点:" + ds.get("boardroom").toString() + 
					"\"," + 
					"\"" + url + "\" : \"" + messageUrl + "\"," + 
	    			"\"pcurl\" : \"" + pcUrl + "\"" + 
				"}]}";
    	}else if("10".equals(type)){//发送提醒
    		message = "{\"articles\" : [{" + 
					"\"title\" : \"会议提醒\"," + 
					"\"description\" : \""+br+ds.get("meetingTitle").toString()+"提醒：" + ds.get("meetingRemindContext") + 
					"\"," + 
					"\"" + url + "\" : \"" + messageUrl + "\"," + 
	    			"\"pcurl\" : \"" + pcUrl + "\"" +  
					"}]}";
    	}
		messageContent.put("news", JsonUtils.readValue(message));
		return messageContent;
	}
	
	private String getBR(String type) {
		if("MH".equals(type)) {
			return "   ";
		}else if("COCALL".equals(type)) {
			return "\\n";
		}
		return "<br>";
	}
	private String getSpace(String type) {
		if("MH".equals(type)) {
			return "   ";
		}else if("COCALL".equals(type)) {
			return "\\t";
		}
		return "<br>";
	}
	
	public static String convertContextPath(String serverUrl){
		 String context = "";
		 serverUrl = serverUrl.substring(serverUrl.lastIndexOf("//")+2,serverUrl.length());
		 int index = serverUrl.lastIndexOf("/");
		 if(index>0){
		      if(index == serverUrl.length()-1){// /在结尾
		        context="";
		      }else{
		        context = serverUrl.substring(serverUrl.lastIndexOf("/")+1);
		      }
		 }else{
		      context="";
		 }
		 return context;
	 }

	 /**
	  * 根据配置文件获取token
	  * @return
	  */
	 public static String getToken(){
		String CLIENT_ID = GlobalConstant.getConfig("app.flexbase.client_id");
		String CLIENT_SECRET = GlobalConstant.getConfig("app.flexbase.client_secret");
		String BASE_URL = GlobalConstant.getConfig("app.flexbase.server.url");
		
		Client client = new Client();
		Map<String, String> params = new HashMap<String, String>();
		params.put("client_id", CLIENT_ID);
		params.put("client_secret", CLIENT_SECRET);
		params.put("grant_type", "client_credentials");

		AccessToken acctessToken = null;
		try {
			acctessToken = client.getToken(BASE_URL + "/oauth2/token", params);
			client.authorizeWithAccessToken(acctessToken);
		} catch (AuthException e) {
			e.printStackTrace();
		}

		if (acctessToken == null) {
			return "";
		}

		return acctessToken.getAccessToken();
	}
	
	 /**
	  * 刪除消息
	  * @param applyRecordId
	  * @param corpId
	  * @param token
	  */
	public void deleteMessage(List<String> dataIds, String corpId, String token) {
		try {
			if(CollectionUtils.isNotEmpty(dataIds)) {
				RestClient restClient = new RestClient(true);
				for(String dataId : dataIds) {
					Map<String, String> params = new HashMap<String, String>();
					params.put("corpId", corpId);
					params.put("dataId", dataId);
					params.put("moduleCode", "meeting");
					restClient.post("/system/umc/message/deleteMessages", token , params);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 
	/**
	 * PC消息提醒
	 * @param paramMap
	 * @param receiver
	 * @param corpId
	 * @param token
	 */
	 public void sendMessage(Map<String, Object> paramMap, String receiver,String corpId, String token){
		 Map<String, String> params = new HashMap<String, String>();
		 String type = StringUtils.null2String(paramMap.get("type"));
		 String dataId = StringUtils.null2String(paramMap.get("applyRecordId"));
		 String languageCode = StringUtils.null2String(paramMap.get("languageCode"));
		 
		 String content = "", msgLink = "";
		 String paramString = "{\"size\": \"row7\"";
		 if("2".equals(type)){//未召开会议邀请
			 String invitatedyou=getRes("oa.meeting.invitatedyou", "${1}邀请您参加${2}！", languageCode, "meeting", corpId, token);
			 content = invitatedyou.replace("${1}", StringUtils.null2String(paramMap.get("userName"))).replace("${2}", StringUtils.null2String(paramMap.get("meetingTitle")));
			 msgLink = "redirectMenu?navId=4028803a61e4349d0161e56aa318003d&menuId=4028803a61e4349d0161e55e2bca0033";
			 params.put("openMode", "1");
		 }else if("3".equals(type)){//取消会议
			 content = paramMap.get("meetingTitle")+"已取消！";
			 msgLink = "modules/meeting/info/applyrecord_view.html";
			 paramString += ", \"applyId\": \""+paramMap.get("applyRecordId")+"\", \"meetingStatus\":\"5\"";
		 }else if("5".equals(type)){//会议纪要
			 String memopublished=getRes("oa.meeting.memopublished", "${1}纪要已发布！", languageCode, "meeting", corpId, token);
			 paramString = "{\"size\": \"fullscreen\"";
			 content =memopublished.replace("${1}", StringUtils.null2String(paramMap.get("meetingTitle")));
			 msgLink = "modules/meeting/memo/memo_view.html";
			 paramString += ", \"applyId\": \""+paramMap.get("applyRecordId")+"\", \"memoId\":\""+paramMap.get("id")+"\"";
		 }else if("4".equals(type)){//会议召开提醒
			 String time = StringUtils.null2String(paramMap.get("noticeTime"));
			 if("5".equals(time)){
				 time = getRes("oa.meeting.min5", "五分钟", languageCode, "meeting", corpId, token);
			 }else if("10".equals(time)){
				 time = getRes("oa.meeting.min10", "十分钟", languageCode, "meeting", corpId, token);
			 }else if("30".equals(time)){
				 time = getRes("oa.meeting.min30", "三十分钟", languageCode, "meeting", corpId, token);
			 }else if("60".equals(time)){
				 time = getRes("oa.meeting.min60", "一小时", languageCode, "meeting", corpId, token);
			 }
			 content = getRes("oa.meeting.pleaseontime", "${1}将于${2}后召开，请准时参会！", languageCode, "meeting", corpId, token).replace("${1}", StringUtils.null2String(paramMap.get("meetingTitle"))).replace("${2}", time);
			 msgLink = "modules/meeting/info/applyrecord_view.html";
			 paramString += ", \"applyId\": \""+paramMap.get("applyRecordId")+"\", \"meetingStatus\":\"1\"";
		 }else if("6".equals(type)){//会议任务
			 dataId = StringUtils.null2String(paramMap.get("id"));
			 content = paramMap.get("userName")+"给您指派了新的会议任务！";
			 msgLink = "modules/meeting/task/taskinfo_view.html";
			 paramString += ", \"taskId\": \""+paramMap.get("id")+"\"";
		 }else if("7".equals(type)){//会议任务到期提醒
			 dataId = StringUtils.null2String(paramMap.get("id"));
			 content = "您的会议任务"+paramMap.get("title")+"即将到期，请尽快完成！";
			 msgLink = "modules/meeting/task/taskinfo_view.html";
			 paramString += ", \"taskId\": \""+paramMap.get("id")+"\"";
		 }else if("8".equals(type)){//未召开会议邀请
			 content = paramMap.get("userName")+"邀请您代替参加"+paramMap.get("meetingTitle");
			 msgLink = "redirectMenu?navId=4028803a61e4349d0161e56aa318003d&menuId=4028803a61e4349d0161e55e2bca0033";
			 params.put("openMode", "1");
		 }else if("9".equals(type)){//会议内容变更提醒
			 content = "变更通知：" + paramMap.get("meetingTitle")+"安排已变更，请及时确认！";
			 msgLink = "modules/meeting/info/applyrecord_view.html";
			 paramString += ", \"applyId\": \""+paramMap.get("applyRecordId")+"\", \"meetingStatus\":\"1\"";
		 }else if("10".equals(type)){//发送提醒
			 content = paramMap.get("meetingTitle")+"提醒：" + paramMap.get("meetingRemindContext");
			 msgLink = "redirectMenu?navId=4028803a61e4349d0161e56aa318003d&menuId=4028803a61e4349d0161e55e2bca0033";
			 params.put("openMode", "1");
		 }
		 paramString += "}";
		 if(StringUtils.isEmpty(dataId)) dataId = UuidUtils.UUID();
		 params.put("corpId", corpId);
		 params.put("dataId", dataId);
		 params.put("moduleCode", "meeting");
		 params.put("moduleId", "402887ba6304b7e4016305aa85d90010");
		 params.put("msgContent", content);
		 params.put("msgFmt", "1");
		 params.put("msgLevel", "3");
		 params.put("msgLink", msgLink);
		 params.put("msgTitle", content);
		 params.put("msgReceiver", receiver);
		 params.put("msgSender", StringUtils.null2String(paramMap.get("userId")));
		 params.put("msgSenderType", "10");
		 params.put("msgType", "1");
		 params.put("paramString", paramString);
		 params.put("createdDate", DateUtils.formatTimeNow());
		 String paramStr = JsonUtils.writeValueAsString(params);
		 SendMsgThread smt = new SendMsgThread(token, "pc", paramStr);
     	 smt.start();
//		 RestClient restClient = new RestClient(true);
//		 String configJson = restClient.post("/system/umc/message/sendmessage", token, new HashMap<String, String>(), paramStr);
//		 Map<String, Object> formContent = JsonUtils.readValue(configJson);
	 }
	
	 /**
	  * 发送邮件消息
	  * @param ds
	  * @param emailPush
	  * @param corpId
	  * @param token
	  */
	public void sendMail(Map<String, Object> ds, boolean emailPush, String corpId, String token) {
		try {
			// 获取系统后台的消息设置(1:内部邮件,2：外部邮件,0：禁用)
			String sysMailType = commonService.getSysParamValueByMark(corpId, token,"sysMailSetting");
			if (StringUtils.isEmpty(sysMailType) || !emailPush || !meetingUtils.getAppInfoMessageSet(corpId, token,"email"))
				return;
			Map<String, String> params = new HashMap<String, String>();
			String theme = getMailTheme(ds);
			String userIds = StringUtils.null2String(ds.get("userIds"));
			String orgIds = StringUtils.null2String(ds.get("orgIds"));
			params.put("sender", StringUtils.null2String(ds.get("userId")));// 发件人
			params.put("recipienters", "{\"u\":\"" + userIds + "\", \"o\":\"" + orgIds + "\"}");// 收件人 u-用户，s-岗位，o-组织，g-群组
			params.put("content", "请进入会议应用查看！");
			params.put("theme", theme);
			params.put("corpId", corpId);
			if (sysMailType.contains("1")) {// 内部邮件
				SendMsgThread smt = new SendMsgThread(token, "email", params);
		     	smt.start();
			}
			if (sysMailType.contains("2")) {// 外部邮件

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 
	private String getMailTheme(Map<String, Object> paramMap) {
		String theme = "";
		String type = StringUtils.null2String(paramMap.get("type"));
		if ("2".equals(type)) {// 未召开会议邀请
			theme = paramMap.get("userName") + "邀请您参加" + paramMap.get("meetingTitle") + "！";
		} else if ("3".equals(type)) {// 取消会议
			theme = paramMap.get("meetingTitle") + "已取消！";
		} else if ("5".equals(type)) {// 会议纪要
			theme = paramMap.get("meetingTitle") + "纪要已发布！";
		} else if ("4".equals(type)) {// 会议召开提醒
			String time = StringUtils.null2String(paramMap.get("noticeTime"));
			if ("5".equals(time)) {
				time = "五分钟";
			} else if ("10".equals(time)) {
				time = "十分钟";
			} else if ("30".equals(time)) {
				time = "三十分钟";
			} else if ("60".equals(time)) {
				time = "一小时";
			}
			theme = paramMap.get("meetingTitle") + "将于" + time + "后召开，请准时参会！";
		} else if ("6".equals(type)) {// 会议任务
			theme = paramMap.get("userName") + "给您指派了新的会议任务！";
		} else if ("7".equals(type)) {// 会议任务到期提醒
			theme = paramMap.get("title") + "即将到期，请尽快完成！";
		} else if ("8".equals(type)) {// 未召开会议邀请
			theme = paramMap.get("userName") + "邀请您代替参加" + paramMap.get("meetingTitle");
		} else if ("9".equals(type)) {// 会议转交通知
			theme = "变更通知：" + paramMap.get("meetingTitle") + "安排已变更，请及时确认！";
		} else if ("10".equals(type)) {// 发送提醒
			theme = paramMap.get("meetingTitle") + "提醒：" + paramMap.get("meetingRemindContext");
		}
		return theme;
	}
	
	/**
	 * 发送短信提醒
	 * @param ds
	 * @param sMSPush
	 * @param corpId
	 * @param token
	 */
	public void sendSMS(Map<String, Object> paramMap, boolean sMSPush, String corpId, String token) {
		try {
			// 获取系统后台的消息设置(1:启用,0：禁用)
			String sysMSMType = commonService.getSysParamValueByMark(corpId, token,"sysSMSsetting");
			if (StringUtils.isEmpty(sysMSMType) || "0".equals(sysMSMType) || !sMSPush || !meetingUtils.getAppInfoMessageSet(corpId, token,"sms")) return;
			RestClient restClient = new RestClient(true);
			Map<String, String> params = new HashMap<String, String>();
			params.put("corpId", corpId);
			params.put("sender", StringUtils.null2String(paramMap.get("userId")));
			params.put("senderOrg", StringUtils.null2String(paramMap.get("userOrg")));
			params.put("receiverIds", StringUtils.null2String(paramMap.get("userIds")));
			params.put("systemName", "本系统");
			params.put("appCode", moduleType);
			paramMap.put("token", token);
			params.put("sendContent", getSMSContent(paramMap));
			params.put("userId", StringUtils.null2String(paramMap.get("userId")));
			Map<String, String> map = new HashMap<String, String>();
			map.put("paramStr", JsonUtils.writeValueAsString(params));
			restClient.post("/sms/savePendingSms", token, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private String getSMSContent(Map<String, Object> paramMap) {
	    Map<String, String> param = new HashMap<String, String>();
	    param.put("corpId", "0");
	    param.put("module", "meeting,meeting.cancel");
		String smsSetStr=new RestClient(true).get("/sms/smsNoticeSetting", (String)paramMap.get("token"), param);
		Map<String, Object> smsSetMap = JsonUtils.readValue(smsSetStr);
		if("0".equals(smsSetMap.get("code"))) {
			List<Map<String,Object>>smsSets=(List<Map<String,Object>>)smsSetMap.get("data");
			if(smsSets.size()>0) {
				paramMap.put("smsSet", smsSets);
			}
		}
		
		String content = "";
		String meetingTime=paramMap.get("startTime").toString()+"~"+paramMap.get("endTime").toString();
		String type = StringUtils.null2String(paramMap.get("type"));
		if ("2".equals(type)) {// 未召开会议邀请
//			content = paramMap.get("userName") + "邀请您参加" + paramMap.get("meetingTitle").toString() +
//					"\n会议时间:" + paramMap.get("startTime").toString() + 
//					"\n会议地点:" + paramMap.get("boardroom").toString();
//			content = "您收到来自"+paramMap.get("userName") + " 的各位领导、同事：会议时间:"+ paramMap.get("startTime").toString()+
//					"在"+ paramMap.get("boardroom").toString() +
//					"召开"+ paramMap.get("meetingTitle").toString() +
//					",请您准时出席。谢谢。详情请您登录协同查看";
			content=getSmsSetContnet(paramMap,"meeting");
			if(content==null) {
				content = meetingTime+"由 "+paramMap.get("emceeUserName").toString()+"主持在"+paramMap.get("boardroom").toString()+"召开"+paramMap.get("meetingTitle").toString()+",请您准时参会。详情请登录办公系统查看并及时回复。"+new SimpleDateFormat("MM-dd HH:mm:ss").format(new Date());
			}
			
		} else if ("3".equals(type)) {// 取消会议
//			content = paramMap.get("meetingTitle").toString() + "已取消" +
//					"\n取消原因:" + paramMap.get("reason").toString();
			content=getSmsSetContnet(paramMap,"meeting.cancel");
			if(content==null) {
				content = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date())+"取消原定于"+meetingTime+"在"+paramMap.get("boardroom").toString()
						+"召开的主题为："+paramMap.get("meetingTitle").toString();
			}
		} else if ("5".equals(type)) {// 会议纪要
			content = paramMap.get("meetingTitle").toString() + "纪要已发布！";
		} else if ("4".equals(type)) {// 会议召开提醒
			String time = StringUtils.null2String(paramMap.get("noticeTime"));
			if ("5".equals(time)) {
				time = "五分钟";
			} else if ("10".equals(time)) {
				time = "十分钟";
			} else if ("30".equals(time)) {
				time = "三十分钟";
			} else if ("60".equals(time)) {
				time = "一小时";
			}
			content = paramMap.get("meetingTitle").toString() + "将于" + time + "后召开，请准时参会" +
					"\n会议时间:" + paramMap.get("startTime").toString() + 
					"\n会议地点:" + paramMap.get("boardroom").toString();
		} else if ("6".equals(type)) {// 会议任务
			content = "您有新的会议任务，请尽快完成"  + 
					"\n任务标题:" + paramMap.get("title").toString() + 
					"\n截止日期:" + paramMap.get("endTime").toString() +
					"\n所属会议:" + paramMap.get("meetingName").toString();
		} else if ("7".equals(type)) {// 会议任务到期提醒
			content = "您的会议任务即将到期，请尽快完成" +
					"\n任务标题:" + paramMap.get("title").toString() + 
    				"\n截止日期:" + paramMap.get("endTime").toString() +
    				"\n所属会议:" + paramMap.get("meetingName").toString();
		} else if ("8".equals(type)) {// 会议转交通知
			content = paramMap.get("userName").toString() + "邀请您代替参加" + paramMap.get("meetingTitle").toString() +
					"\n会议时间:" + paramMap.get("startTime").toString() +
    				"\n会议地点:" + paramMap.get("boardroom").toString();
		} else if ("9".equals(type)) {// 会议内容变更提醒
			content = "变更通知:" + paramMap.get("meetingTitle").toString() + "安排已变更，请及时确认" +
					"\n会议时间:" + paramMap.get("startTime").toString() +
    				"\n会议地点:" + paramMap.get("boardroom").toString();
		} else if ("10".equals(type)) {// 发送提醒
			content = paramMap.get("meetingTitle").toString() + "提醒:" + paramMap.get("meetingRemindContext").toString();
		}
		return content;
	}
	
	@SuppressWarnings("unchecked")
	public String getRes(String key,String defaultValue,String languageCode,String modules,String corpId, String token){
		if(StringUtils.isBlank(languageCode)||StringUtils.isBlank(key)) {
			return defaultValue;
		}
		RestClient restClient=new RestClient(true);
		String reValue="";
		List<Map<String, String>>cache = (List<Map<String, String>>)CacheUtils.get(languageCode+ " "+modules+" "+corpId);
		if(cache==null || cache.size()<1) {
			
			Map<String,String>param=new HashMap<>();
			param.put("languageCode", languageCode);
			param.put("corpId", corpId);
			param.put("modules", modules);
			String json=restClient.get("/system/i18n/getResource", token, param);
			Map<String, Object> rmap=JsonUtils.readValue(json);
			CacheUtils.put(languageCode+ " "+modules+" "+corpId,rmap.get("data"));
		}
		cache= (List<Map<String, String>>)CacheUtils.get(languageCode+ " "+modules+" "+corpId);
		if(cache!=null && cache.size()>0) {
			for(Map<String, String> ele:cache) {
				if(ele.get(key)!=null) {
					reValue=ele.get(key);
					break;
				}
			}
		}
		if("".equals(reValue)||reValue==null) {
			return defaultValue;
		}
		return reValue;
	}
	
	/**
	 * 获取后台设置的短信内容
	 * @param paramMap
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getSmsSetContnet(Map<String, Object> paramMap,String module) {
		List<Map<String, Object>> smsSets = (List<Map<String, Object>>) paramMap.get("smsSet");
		if (smsSets != null) {
			for(Map<String, Object> smsSet:smsSets) {
				if(module.equals(smsSet.get("module"))) {
					if("1".equals(smsSet.get(module+"_enable"))) {
						String select2 = StringUtils.null2String(smsSet.get(module+"_select2"));
						String select4 = StringUtils.null2String(smsSet.get(module+"_select4"));
						String select6 = StringUtils.null2String(smsSet.get(module+"_select6"));
						String select8 = StringUtils.null2String(smsSet.get(module+"_select8"));
						String select10 = StringUtils.null2String(smsSet.get(module+"_select10"));
						StringBuffer smsMessage = new StringBuffer();
						smsMessage.append(smsSet.get(module+"_text1"));
						smsMessage.append(getSelect(select2,paramMap));
						smsMessage.append(smsSet.get(module+"_text3"));
						smsMessage.append(getSelect(select4,paramMap));
						smsMessage.append(smsSet.get(module+"_text5"));
						smsMessage.append(getSelect(select6,paramMap));
						smsMessage.append(smsSet.get(module+"_text7"));
						smsMessage.append(getSelect(select8,paramMap));
						smsMessage.append(smsSet.get(module+"_text9"));
						smsMessage.append(getSelect(select10,paramMap));
						return smsMessage.toString();
					}
					return null;
				}
			}
			
		}
		return null;
	}

	public String getSelect(String select,Map<String, Object>paramMap) {
		if ("title".equals(select)) {
			select=StringUtils.null2String(paramMap.get("meetingTitle"));
		} else if ("sender".equals(select)) {
			select=StringUtils.null2String(paramMap.get("userName"));
		} else if ("department".equals(select)) {
			select=cmpPopUserOrgName.getOrgNameById(StringUtils.null2String(paramMap.get("userOrg")));
		} else if ("date".equals(select)) {
			select=StringUtils.null2String(paramMap.get("startTime"))+"-"+StringUtils.null2String(paramMap.get("endTime"));
		} else if ("blank".equals(select)) {
			select="";
		}
		return select;
	}
}
